<template>
  <div class="content">
    <!-- 输入框 -->
    <van-field
      v-model="sms"
      center
      clearable
      label="短信验证码"
      placeholder="请输入短信验证码"
    >
      <template #button>
        <van-button size="small" class="send" :disabled="!sendFlag" @click="sendCode" type="primary">{{ sendTip }}</van-button>
      </template>
    </van-field>
    <!-- 提交按钮 -->
    <van-button round type="info" @click="submitCode" size="large" color="#f2270c" :disabled="!flag">确定注册</van-button>
  </div>
</template>

<script>
import Vue from 'vue'
import { Field, Button, Toast } from 'vant'
import { getCode, docheckcode } from '@/api/user'

Vue.use(Field)
Vue.use(Button)
export default {
  data () {
    return {
      sms: '',
      sendTip: '发送验证码',
      time: -1
    }
  },
  computed: {
    flag () {
      return /\d{5}/.test(this.sms)
    },
    sendFlag () {
      return this.time < 0
    }
  },
  methods: {
    async sendCode () {
      var tel = localStorage.getItem('tel')
      var res = await getCode(tel)
      console.log(res)
      this.time = 5
      var sendtime = setInterval(() => {
        this.time--
        this.sendTip = this.time + 's发送验证码'
        if (this.time < 0) {
          this.sendTip = '发送验证码'
          clearInterval(sendtime)
        }
      }, 1000)
    },
    async submitCode () {
      var res = await docheckcode({ tel: localStorage.getItem('tel'), telcode: this.sms.toString() })
      if (res.code === '200') this.$router.push('/register/register3')
      else Toast('验证码错误')
    }
  }
}
</script>

<style lang="stylus" scoped>
body
  background-color #fff
.send
  border none
  background-color white
  color black
</style>
